package com.shengchang.hu.supervision.UI;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.zyapi.CommonApi;

import com.google.gson.JsonObject;
import com.magicrf.uhfreader.UhfReaderDevice;
import com.magicrf.uhfreader.Util;
import com.magicrf.uhfreaderlib.reader.Tools;
import com.magicrf.uhfreaderlib.reader.UhfReader;
import com.olc.mode.readmode;
import com.olc.uhf.tech.ISO1800_6C;
import com.olc.uhf.tech.IUhfCallback;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.RFID.DevBeep;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.Contants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import NFC.NdefMessageParser;
import NFC.ParsedNdefRecord;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class CheckedActivity extends BaseActivity {
//    @BindView(R.id.checkedbar)
    InBoundBar checkedbar;
    private static final DateFormat TIME_FORMAT = SimpleDateFormat
            .getDateTimeInstance();
    private  String departmentname;
    private  String departmentid;
    private  String maccode;
    private ISO1800_6C uhf_6c;
    int allcount = 0;
    private boolean isLoop =false;
    private Handler mHandler = new MainHandler();
    private  static  final  String DEPARTMENT_API=Contants.DEPARTMENT_API;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_checked);
        checkedbar=findViewById(R.id.checkedbar);
        checkedbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
//        resolveIntent(getIntent());
        Intent intent = getIntent();
        maccode = intent.getStringExtra("maccode");
        openRfid();

//        mDialog = new AlertDialog.Builder(this).setNeutralButton("Ok", null)
//                .create();
//
//        // 获取默认的NFC控制器
//        mAdapter = NfcAdapter.getDefaultAdapter(this);
//
//        //拦截系统级的NFC扫描，例如扫描蓝牙
//        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
//                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
//        mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord("",
//                Locale.ENGLISH, true) });
        }

    private void openRfid() {

        if(App.mService!=null)
        {
            uhf_6c = (ISO1800_6C) App.mService.getISO1800_6C();
            DevBeep.init(CheckedActivity.this);
//            if(getInfo().startsWith("M18")){
//                if(App.mversion.equals("")){
//                    App.mversion=App.mService.getModuleInformation((byte)0x01);
//                }
//            }
        }
        else
        {
            //Camera.Parameters parameters;
            //parameters .setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        initview();
    }

    private void initview() {
           if (!isLoop){

               isLoop = true;
               LoopReadEPC();

           }

    }

    @Override
    protected void onResume() {
        super.onResume();

//        if (mAdapter == null) {
//            if (!mAdapter.isEnabled()) {
//                showWirelessSettingsDialog();
//            }
//
//            showMessage("error", " NO NFC");
//            showShortToast("设备不支持NFC");
//
//
//            return;
//        }
//        if (!mAdapter.isEnabled()) {
//            showShortToast("请在系统设置中先启用NFC功能");
//
//            return;
//        }
//
//        if (mAdapter != null) {
//            //隐式启动
//            mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
//            mAdapter.enableForegroundNdefPush(this, mNdefPushMessage);
//        }



    }
//    public void registerBroadcast() {
//        final IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(m_Broadcastname);
//        registerReceiver(receiver, intentFilter);
//    }
//
//    public class MyCodeReceiver extends BroadcastReceiver
//    {
//        private static final String TAG = "MycodeReceiver";
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if(intent.getAction().equals(m_Broadcastname)) {
//                String str = intent.getStringExtra("BARCODE");
//                if (!"".equals(str)) {
//                    showProgressDialog();
//                    CheckedRequest(str);
//
//
//                }
//            }
//        }
//    }
    @Override
    protected void onPause() {
        super.onPause();

        isLoop=false;
//        if (mAdapter != null) {
//            //隐式启动
//            mAdapter.disableForegroundDispatch(this);
//            mAdapter.disableForegroundNdefPush(this);
//        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isLoop = false;
            App.mService.close();
            System.exit(0);
        }
        return super.onKeyDown(keyCode, event);
    }


    public void LoopReadEPC() {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isLoop) {
                    uhf_6c.inventory(callback);
                    if (!isLoop) {
                        break;
                    }
                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;

                    }
                }
            }
        });
        thread.start();
    }

    private class MainHandler extends Handler {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {

              final   String readerdata = (String) msg.obj;

                if (readerdata!=null&&!TextUtils.isEmpty(readerdata)){

                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            showProgressDialog();
                            CheckedRequest(readerdata);

                        }
                    },0);


                }
                isLoop = false;
                Log.d("uuieoowqq", readerdata);
//                {
//                    model.setTIDNo("");
//                    model.setEPCNo(readerdata);
//
////                    adapter.notifyDataSetChanged();
//                }
                // m_number++;
//                IshavaCode(model, 1);
            }

        }
    };

    IUhfCallback callback = new IUhfCallback.Stub() {
        @Override
        public void doInventory(List<String> str) throws RemoteException {
            // for (Iterator it2 = str.iterator(); it2.hasNext();)
            Log.d("dqw", "count111=" + str.size());
            allcount += str.size();
            Log.d("dqw00000007", "count111=" + allcount);

            for (int i = 0; i < str.size(); i++) {
                String strepc = (String) str.get(i);
                Log.d("wyt", "RSSI=" + strepc.substring(0, 2));
                Log.d("wyt", "PC=" + strepc.substring(2, 6));
                Log.d("wyt", "EPC=" + strepc.substring(6));
                DevBeep.PlayOK();
                String strEpc = strepc.substring(2, 6) + strepc.substring(6);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = strEpc;
                mHandler.sendMessage(msg);
            }
        }

        @Override
        public void doTIDAndEPC(List<String> str) throws RemoteException {
            for (Iterator it2 = str.iterator(); it2.hasNext();) {
                String strepc = (String) it2.next();
                // Log.d("wyt", strepc);
                int nlen = Integer.valueOf(strepc.substring(0, 2), 16);
                // Log.d("wyt", "PC=" + strepc.substring(2, 6));
                // Log.d("wyt", "EPC=" + strepc.substring(6, (nlen + 1) * 2));
                // Log.d("wyt", "TID=" + strepc.substring((nlen + 1) * 2));

            }
        }

    };

//    private void showMessage(String title, String message) {
//        mDialog.setTitle(title);
//        mDialog.setMessage(message);
//        mDialog.show();
//    }
//
//    private NdefRecord newTextRecord(String text, Locale locale,
//                                     boolean encodeInUtf8) {
//        byte[] langBytes = locale.getLanguage().getBytes(
//                Charset.forName("US-ASCII"));
//
//        Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
//                .forName("UTF-16");
//        byte[] textBytes = text.getBytes(utfEncoding);
//
//        int utfBit = encodeInUtf8 ? 0 : (1 << 7);
//        char status = (char) (utfBit + langBytes.length);
//
//        byte[] data = new byte[1 + langBytes.length + textBytes.length];
//        data[0] = (byte) status;
//        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
//        System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
//                textBytes.length);
//
//        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
//                new byte[0], data);
//    }
//
//    private void showWirelessSettingsDialog() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setMessage("nfc_disabled");
//        builder.setPositiveButton(android.R.string.ok,
//                new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        Intent intent = new Intent(
//                                Settings.ACTION_WIRELESS_SETTINGS);
//                        startActivity(intent);
//                    }
//                });
//        builder.setNegativeButton(android.R.string.cancel,
//                new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        finish();
//                    }
//                });
//        builder.create().show();
//        return;
//    }

//初步判断是什么类型NFC卡
//private void resolveIntent(Intent intent) {
//    String action = intent.getAction();
//    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
//            || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
//            || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
//        Parcelable[] rawMsgs = intent
//                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
//        NdefMessage[] msgs;
//        if (rawMsgs != null) {
//            msgs = new NdefMessage[rawMsgs.length];
//            for (int i = 0; i < rawMsgs.length; i++) {
//                msgs[i] = (NdefMessage) rawMsgs[i];
//            }
//        } else {
//            // Unknown tag type
//            byte[] empty = new byte[0];
//            byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
//            Parcelable tag = intent
//                    .getParcelableExtra(NfcAdapter.EXTRA_TAG);
//            byte[] payload = dumpTagData(tag).getBytes();
//            NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN,
//                    empty, id, payload);
//            NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
//            msgs = new NdefMessage[] { msg };
//        }
//        // Setup the views
//
////        showShortToast("");
//        buildTagViews(msgs);
//    }
//}
//
//    //一般公家卡，扫描的信息
//    private String dumpTagData(Parcelable p) {
//        StringBuilder sb = new StringBuilder();
//        Tag tag = (Tag) p;
//        byte[] id = tag.getId();
//        sb.append("Tag ID (hex): ").append(getHex(id)).append("\n");
//        sb.append("Tag ID (dec): ").append(getDec(id)).append("\n");
//        sb.append("ID (reversed): ").append(getReversed(id)).append("\n");
//
//        String prefix = "android.nfc.tech.";
//        sb.append("Technologies: ");
//        for (String tech : tag.getTechList()) {
//            sb.append(tech.substring(prefix.length()));
//            sb.append(", ");
//        }
//        sb.delete(sb.length() - 2, sb.length());
//        for (String tech : tag.getTechList()) {
//            if (tech.equals(MifareClassic.class.getName())) {
//                sb.append('\n');
//                MifareClassic mifareTag = MifareClassic.get(tag);
//                String type = "Unknown";
//                switch (mifareTag.getType()) {
//                    case MifareClassic.TYPE_CLASSIC:
//                        type = "Classic";
//                        break;
//                    case MifareClassic.TYPE_PLUS:
//                        type = "Plus";
//                        break;
//                    case MifareClassic.TYPE_PRO:
//                        type = "Pro";
//                        break;
//                }
//                sb.append("Mifare Classic type: ");
//                sb.append(type);
//                sb.append('\n');
//
//                sb.append("Mifare size: ");
//                sb.append(mifareTag.getSize() + " bytes");
//                sb.append('\n');
//
//                sb.append("Mifare sectors: ");
//                sb.append(mifareTag.getSectorCount());
//                sb.append('\n');
//
//                sb.append("Mifare blocks: ");
//                sb.append(mifareTag.getBlockCount());
//            }
//
//            if (tech.equals(MifareUltralight.class.getName())) {
//                sb.append('\n');
//                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
//                String type = "Unknown";
//                switch (mifareUlTag.getType()) {
//                    case MifareUltralight.TYPE_ULTRALIGHT:
//                        type = "Ultralight";
//                        break;
//                    case MifareUltralight.TYPE_ULTRALIGHT_C:
//                        type = "Ultralight C";
//                        break;
//                }
//                sb.append("Mifare Ultralight type: ");
//                sb.append(type);
//            }
//        }
//
//        return sb.toString();
//    }
//
//    private String getHex(byte[] bytes) {
//        StringBuilder sb = new StringBuilder();
//        for (int i = bytes.length - 1; i >= 0; --i) {
//            int b = bytes[i] & 0xff;
//            if (b < 0x10)
//                sb.append('0');
//            sb.append(Integer.toHexString(b));
//            if (i > 0) {
//                sb.append(" ");
//            }
//        }
//        return sb.toString();
//    }
//
//    private long getDec(byte[] bytes) {
//        long result = 0;
//        long factor = 1;
//        for (int i = 0; i < bytes.length; ++i) {
//            long value = bytes[i] & 0xffl;
//            result += value * factor;
//            factor *= 256l;
//        }
//        return result;
//    }
//
//    private long getReversed(byte[] bytes) {
//        long result = 0;
//        long factor = 1;
//        for (int i = bytes.length - 1; i >= 0; --i) {
//            long value = bytes[i] & 0xffl;
//            result += value * factor;
//            factor *= 256l;
//        }
//        return result;
//    }

    //16进制字符串转换为String
//    private String hexString = "0123456789ABCDEF";
//    public String decode(String bytes) {
//        if (bytes.length() != 30) {
//            return null;
//        }
//        ByteArrayOutputStream baos = new ByteArrayOutputStream(
//                bytes.length() / 2);
//        // 将每2位16进制整数组装成一个字节
//        for (int i = 0; i < bytes.length(); i += 2)
//            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
//                    .indexOf(bytes.charAt(i + 1))));
//        return new String(baos.toByteArray());
//    }
    //显示NFC扫描的数据
//    private void buildTagViews(NdefMessage[] msgs) {
//        if (msgs == null || msgs.length == 0) {
//            return;
//        }
//        Date now = new Date();
//        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
//        final int size = records.size();
//        for (int i = 0; i < size; i++) {
//            TextView timeView = new TextView(this);
//            timeView.setText(TIME_FORMAT.format(now));
//            ParsedNdefRecord record = records.get(i);
//
////            showShortToast(String.valueOf(record.getViewText()));
//            String viewText = record.getViewText();
//            String[] split = viewText.split("\\n");
//            String[] split2 = split[1].split(" ");
//            final String string = split2[3];
//            Log.d("jdeuidia", string);
//           if (!TextUtils.isEmpty(string) &&  string.length()>9){
//               new Thread(new Runnable() {
//                   @Override
//                   public void run() {
//
//                       try {
//
//                           Handler handler = new Handler(Looper.getMainLooper());
//                           handler.post(new Runnable() {
//                               @Override
//                               public void run() {
//                                   showProgressDialog();
//                                   CheckedRequest(string);
//
//                                   }
//                                   });
//                           } catch (InputMismatchException e) {
//                           e.printStackTrace();
//                           }
//
//                           }
//                           }).start();
////               showShortToast(string);
////               Log.d("record", String.valueOf(record.getViewText()));
//           }else  if (!TextUtils.isEmpty(string) &&  string.length()<=9){
//             final  String  s="0"+string;
//               new Thread(new Runnable() {
//                   @Override
//                   public void run() {
//
//                       try {
//
//                           Handler handler = new Handler(Looper.getMainLooper());
//                           handler.post(new Runnable() {
//                               @Override
//                               public void run() {
//                                   showProgressDialog();
//                                   CheckedRequest(s);
//
//                               }
//                           });
//                       } catch (InputMismatchException e) {
//                           e.printStackTrace();
//                       }
//
//                   }
//               }).start();
//           }else{
//               showShortToast("读卡失败");
//           }
//
//            }
//    }

    //获取系统隐式启动的
//    @Override
//    public void onNewIntent(Intent intent) {
//        setIntent(intent);
//        resolveIntent(intent);
//    }
    private void CheckedRequest(String uhfdata) {
        OkHttpClient moKhttp=new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("id",App.getApp().getToken())
                .add("cardCode",uhfdata)
                .build();
        Request request = new Request.Builder()
                .url(DEPARTMENT_API)
                .post(formBody)
                .build();
        Log.d("DEPARTMENT_API",DEPARTMENT_API+"?id="+App.getApp().getToken()+"&cardCode="+uhfdata);
        Call call = moKhttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }				});				//此处会发生异常//
                    }		}).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final   String  Departmentstr=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DepartmentRequest(Departmentstr);
                    }
                });

            }
        });

        }

    private void DepartmentRequest(String departmentstr) {
        try {
            JSONObject  Departmentjson=new JSONObject(departmentstr);
            String  DepartmentMsg=Departmentjson.getString("message");
            if (DepartmentMsg.equals("20004")){
                dismissProgressDialog();
                showShortToast("网络请求异常");
                OpenDelay();

            }else if(DepartmentMsg.equals("20005")){
                dismissProgressDialog();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {

                                Intent intent = new Intent(CheckedActivity.this, InBoundActivity.class);
                                 intent.putExtra("Ufhdata", departmentname);
                                 intent.putExtra("departmentid",departmentid);
                                 intent.putExtra("maccode",maccode);
                                 startActivity(intent);
                                    finish();
                            }
                        });				//此处会发生异常//
                    }		}).start();

            }else  if (DepartmentMsg.equals("20008")){
                dismissProgressDialog();
                showShortToast("查无此卡");
                OpenDelay();
            } else if (DepartmentMsg.equals("20009")){
                dismissProgressDialog();
                showShortToast("类型不符合");
                OpenDelay();
            } else if (DepartmentMsg.equals("20014")){
                dismissProgressDialog();
                showShortToast("机构不符合");
                OpenDelay();
            } else if (DepartmentMsg.equals("20020")){
                dismissProgressDialog();
                showShortToast("请先结束收集");
                OpenDelay();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject  mJson=new JSONObject(departmentstr);
            JSONObject jsonObject = mJson.getJSONObject("department");
            departmentname=jsonObject.getString("departmentName");
            departmentid=jsonObject.getString("departmentId");
            Log.d("hdueiw",  departmentid);


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void OpenDelay() {
        if (!isLoop){
            Handler  mhandler=new Handler();
            mhandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isLoop = true;
                    LoopReadEPC();
                }
            },3000);


        }
    }


    @Override
    protected void onStop() {
        super.onStop();



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isLoop = false;
        App.mService.close();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
